package panda.metainfo;

import panda.index.Index;
import panda.record.*;
import panda.transaction.*;
import panda.server.*;
import panda.index.bplustree.*;
import panda.query.struct.*;
import static panda.file.Page.BLOCK_SIZE;
import static java.sql.Types.*;

public class IndexToken {
	private String idxname, fieldname;
	private Transaction tx;
	private StaticInfo si;
	private TableToken tt;
	
	IndexToken(String idx, String tblname, String field, Transaction t) {
		idxname = idx;
		fieldname = field;
		tx = t;
		tt = Panda.getMetaInfoManager().getTableToken(tblname, tx);
		si = Panda.getMetaInfoManager().getStaticInfo(tblname, tt, tx);
	}
	
	public Index open() {
		Schema sch = schema();
		return new TreeIndex(idxname, tx, sch);
	}
	
	public int blockAccessed() {
		int rpb = BLOCK_SIZE / tt.getTupleLength();
		int blocknum = si.getOutputSize() / rpb;
		
		return TreeIndex.searchCost(blocknum, rpb);
	}
	
	public int outputSize() {
		return si.getOutputSize() / si.getDistinctSize(fieldname);
	}
	
	public int distinctSize(Attribute name) {
		if (fieldname.equals(name)) return 1;
		else return Math.min(si.getDistinctSize(fieldname), outputSize());
	}
	
	private Schema schema() {
		Schema sch = new Schema();
		sch.addIntAttr(new SemAttribute("blocknum"));
		sch.addIntAttr(new SemAttribute("id"));
		
		if (tt.getSchema().getType(fieldname) == INTEGER) {
			sch.addIntAttr(new SemAttribute("dataval"));
		}
		else {
			int len = tt.getSchema().getLength(fieldname);
			sch.addAttribute(new SemAttribute("dataval"), VARCHAR, len);
		}
		return sch;
	}
}
